import 'dart:convert';

import 'package:get/get.dart';
import 'package:intl/intl.dart';
import 'package:seedfour/app/models/income_alloc_content_entity.dart';
import 'package:seedfour/app/models/income_invoice_entity.dart';
import 'package:seedfour/app/models/income_order_list_entity.dart';
import 'package:seedfour/app/routes/app_routes.dart';

import '../../../remote/request.dart';
import '../../../services/api_service.dart';
import '../order_income/logic.dart';

class OrderIncomeDetailLogic extends GetxController {
  final listLogic = Get.find<OrderIncomeLogic>();

  final apiService = Get.find<ApiService>();

  final orderDetail = Rxn<IncomeOrderInfo>();
  final invoiceDetail = Rxn<IncomeInvoiceEntity>();

  final orderInfo = <String, String>{}.obs;
  final invoiceInfo = <String, String>{}.obs;
  final depositInfo = <String, String>{}.obs;
  final settlementInfo = <String, String>{}.obs;

  final hasInvoice = false.obs;
  final hasDeposit = false.obs;
  final hasSettlement = false.obs;
  final showCancel = false.obs;

  final changeInvoiceText = ''.obs;
  final returnRefresh = false.obs;

  final caseList = <IncomeInvoiceRelateCases>[].obs;

  @override
  void onInit() {
    super.onInit();
    orderDetail.value = Get.arguments;
    invoiceDetail.value = IncomeInvoiceEntity.fromJson(
        jsonDecode(orderDetail.value!.invoice ?? ''));

    orderInfo['付款账户'] = orderDetail.value!.title ?? '';
    orderInfo['创建人'] = orderDetail.value!.creatorName ?? '';
    orderInfo['手机号'] = orderDetail.value!.mobile ?? '';
    orderInfo['创建时间'] = DateFormat('yyyy.MM.dd HH:mm').format(
        DateTime.fromMillisecondsSinceEpoch(orderDetail.value!.createdAt!));
    orderInfo['更新时间'] = DateFormat('yyyy.MM.dd HH:mm').format(
        DateTime.fromMillisecondsSinceEpoch(orderDetail.value!.updatedAt!));
    orderInfo['订单号'] = orderDetail.value!.id ?? '';

    hasDeposit.value = orderDetail.value!.collectionDate != 0 &&
        orderDetail.value!.marginAmount != null;
    if (hasDeposit.value) {
      depositInfo['押金金额'] = orderDetail.value!.marginAmount.toString();
      depositInfo['结算状态'] =
          orderDetail.value!.marginDate == null ? '未结算' : '已结算';
    }

    settlementInfo['分配比例'] = orderDetail.value!.settle!.ratio!;
    settlementInfo['余额金额'] = orderDetail.value!.settle!.settleAmount!;

    if (orderDetail.value!.allocContent != null) {
      IncomeAllocContentEntity allocContent = IncomeAllocContentEntity.fromJson(
          jsonDecode(orderDetail.value!.allocContent ?? '{}'));
      settlementInfo['专款金额'] = '¥${allocContent.remain.amount}';
    } else {
      settlementInfo['专款金额'] = '¥0';
    }
    settlementInfo['押金金额'] = '¥${orderDetail.value!.marginAmount}';

    _initInvoiceInfo();

    showCancel.value = orderDetail.value!.orderStatus == 0 &&
        orderDetail.value!.invoiceStatus != 1;

    caseList.value = invoiceDetail.value!.relateCases ?? [];
  }

  void onClickCase(int index) {
    Get.toNamed(RouteGet.caseDetail, arguments: caseList[index].caseId);
  }

  void _initInvoiceInfo() {
    invoiceInfo['发票状态'] = listLogic.invoiceStatus(orderDetail.value!);
    hasInvoice.value = invoiceDetail.value != null &&
        invoiceDetail.value!.taxid != null &&
        invoiceDetail.value!.taxid!.isNotEmpty;
    if (hasInvoice.value) {
      if (invoiceDetail.value!.showTab != null &&
          invoiceDetail.value!.showTab == 'onlineArchive') {
        invoiceInfo['电子邮箱'] = invoiceDetail.value!.email ?? '';
      }
      invoiceInfo['纳税人识别号'] = invoiceDetail.value!.taxid ?? '';
      invoiceInfo['应税名称'] = invoiceDetail.value!.cargo ?? '';
      invoiceInfo['地址'] = invoiceDetail.value!.address ?? '';
      invoiceInfo['电话'] = invoiceDetail.value!.phone ?? '';
      invoiceInfo['开户银行'] = invoiceDetail.value!.bankname ?? '';
      invoiceInfo['银行账号'] = invoiceDetail.value!.bankacct ?? '';
      invoiceInfo['备注'] = invoiceDetail.value!.remark ?? '';
    }

    changeInvoiceText.value = hasInvoice.value ? '修改发票' : '补开发票';
  }

  void changeInvoice() async {
    final result = await Get.toNamed(RouteGet.incomeOrderCreate,
        arguments: orderDetail.value);

    if (result != null && result is IncomeInvoiceEntity) {
      returnRefresh.value = true;
      invoiceDetail.value = result;
      orderDetail.value!.invoiceStatus = 0;

      _initInvoiceInfo();
    }
  }

  void cancelOrder() => request(
        () async {
          var result = await apiService.deleteOrder(orderDetail.value!.id!);

          if (result != null) {
            Get.back(result: true);
          }
        },
        showLoading: true,
        message: '取消中...',
      );
}
